<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import { createAdvertPosition, updateAdvertPosition, getAdvertPositionDetail } from '@/api/advertPosition/admin'
import { ContentWrap } from '@/components/ContentWrap'
import type { AdvertPositionCreateOrUpdateParams } from '@/api/advertPosition/types'

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>()

// 路由和路由参数
const router = useRouter()
const route = useRoute()

// 判断是否为编辑模式
const isEdit = ref(false)

// 表单数据
const form = reactive<AdvertPositionCreateOrUpdateParams>({
  name: '',
  title: '',
  sizeInfo: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入广告位名称', trigger: 'blur' }],
  title: [{ required: true, message: '请输入广告位标题', trigger: 'blur' }],
  sizeInfo: [{ required: true, message: '请输入尺寸信息', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 加载状态
const loading = ref(false)

// 获取广告位详情
const fetchAdvertPositionDetail = async (id: string) => {
  try {
    loading.value = true
    const response = await getAdvertPositionDetail(Number(id))
    if (response.code === 200) {
      Object.assign(form, response.data)
    } else {
      ElMessage.error(response.message || '获取广告位详情失败')
    }
  } catch (error) {
    ElMessage.error('获取广告位详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        let response
        
        if (isEdit.value) {
          // 编辑模式
          response = await updateAdvertPosition(form.id!, form)
        } else {
          // 新增模式
          response = await createAdvertPosition(form)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          if (route.query.from === 'config') {
            router.push({ name: 'AdvertPositionConfig', query: { refresh: '1' } })
          } else {
            router.push({ name: 'AdvertPositionPageList', query: { refresh: '1' } })
          }
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回列表页
const goBack = () => {
  if (route.query.from === 'config') {
    router.push({ name: 'AdvertPositionConfig' })
  } else {
    router.push({ name: 'AdvertPositionPageList' })
  }
}

// 初始化
onMounted(() => {
  const id = route.params.id as string
  if (id && id !== '0') {
    isEdit.value = true
    fetchAdvertPositionDetail(id)
  }
})
</script>

<template>
  <ContentWrap
    :title="isEdit ? '编辑广告位' : '新增广告位'"
    :message="isEdit ? '编辑广告位信息' : '添加新的广告位信息'"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="max-width: 500px"
      :disabled="loading"
    >
      <el-form-item label="广告位名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入广告位名称" />
      </el-form-item>

      <el-form-item label="广告位标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入广告位标题" />
      </el-form-item>

      <el-form-item label="尺寸信息" prop="sizeInfo">
        <el-input v-model="form.sizeInfo" placeholder="请输入尺寸信息" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="loading">
          {{ isEdit ? '更新' : '提交' }}
        </el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<style scoped>
:deep(.el-form-item__content) {
  justify-content: flex-start;
}
</style>